package com.user.utils;

import com.alibaba.fastjson.JSONObject;
import com.user.dao.WeatherDao;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.util.ArrayList;
import java.util.List;


public class WeatherFactorGenerator {

    public static List<WeatherDao> fetchWeatherData(double latitude, double longitude, String startDate, String endDate) {
        String apiUrl = String.format("https://api.open-meteo.com/v1/forecast?latitude=%f&longitude=%f&daily=temperature_2m_max,temperature_2m_min,precipitation_sum&timezone=auto&start_date=%s&end_date=%s", latitude, longitude, startDate, endDate);
        HttpClient client = HttpClients.createDefault();
        HttpGet request = new HttpGet(apiUrl);
        List<WeatherDao> weatherDaoList = new ArrayList<>();

        try {
            String response = EntityUtils.toString(client.execute(request).getEntity());
            JSONObject jsonResponse = JSONObject.parseObject(response);
            JSONObject forecasts = jsonResponse.getJSONObject("daily");
            double[] maxTemperatures = forecasts.getJSONArray("temperature_2m_max").toJavaObject(double[].class);
            double[] minTemperatures = forecasts.getJSONArray("temperature_2m_min").toJavaObject(double[].class);
            double[] precipitationSums = forecasts.getJSONArray("precipitation_sum").toJavaObject(double[].class);
            String[] dates = forecasts.getJSONArray("time").toJavaObject(String[].class);


            for (int i = 0; i < maxTemperatures.length; i++) {
                WeatherDao weatherDao = new WeatherDao();
                double dailyAverageTemperature = Math.round(((maxTemperatures[i] + minTemperatures[i]) / 2) * 100.0) / 100.0;
                weatherDao.setDate(dates[i]);
                weatherDao.setAverageTemperature(dailyAverageTemperature);
                weatherDao.setPrecipitation(precipitationSums[i]);
                weatherDaoList.add(weatherDao);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return weatherDaoList;
    }


    public static void main(String[] args) {
        WeatherFactorGenerator.fetchWeatherData(29.5603, 106.5577, "2024-05-19", "2024-05-31");
    }
}